//
//  KALoanAgreement.swift
//  kano
//
//  Created by Frank on 2024/9/26.
//

import Foundation
import UIKit

class KALoanAgreement: KABaseVC {
    var textView: UITextView!
    
    var loanDate = ""
    var loanName = ""
    var loanAddress = "aaaaaaa"
    var loanMoney = ""
    var loanInterest = ""
    var loanDay = ""
    var repaymentDate = ""
    var penaltyInterest = "1.7%/day~3%/day"
    
    var detailModel: KABillDetailModel?
    
    init(with model: KABillDetailModel) {
        super.init(nibName: nil, bundle: nil)
        detailModel = model
        loanDate = Date.ka_stringWith(timestamp: model.loanTimeline, format: "dd/MM/yyyy")
        loanMoney = "\(model.overdueStatus)"//"\(model.registrationConfirmation)"
        loanDay = "\(model.loanDuration)"
        //        if model.loanDuration == 360 {
        //            loanInterest = "\(model.registrationConfirmation * 8 / 10000 * 14)"
        //        } else {
        //            loanInterest = "\(model.registrationConfirmation * 8 / 10000 * model.loanDuration)"
        //        }
        
        let formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy"
        formatter.timeZone = TimeZone.current
        formatter.calendar = Calendar(identifier: .gregorian)

        let dateStrings = model.dueDateArr.map { timestamp -> String in
            let date = Date(timeIntervalSince1970: timestamp)
            return formatter.string(from: date)
        }
        let resultString = dateStrings.joined(separator: "、")
        
        repaymentDate = resultString
        loanAddress = "\(model.productIdentifier)"
        loanName = "\(model.optOutURL)"
        //penaltyInterest = "\(model.overdueFee)"
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Loan Agreement"
        
        textView = UITextView(frame: CGRect(x: 0, y: UIDevice.ka_fullNavHeight, width: var_screenWidth, height: UIDevice.ka_viewHeight))
        textView.backgroundColor = .white
        textView.font = UIFont.systemFont(ofSize: 16)
        textView.textColor = UIColor.black
        textView.isEditable = false
        textView.isSelectable = true
        textView.dataDetectorTypes = [.link]
        view.addSubview(textView)
        
        //        requstData()
        loadHTMLContent()
    }
    
    func requstData() {
        
        let paraDic = [ "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions ]
        view.showLoading()
        billProvider.request(.userInfo(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            loanName = content.voucherImageURL
                            //        loanAddress =
                            loadHTMLContent()
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
}

extension KALoanAgreement {
    func loadHTMLContent() {
        let htmlString = """
            <!DOCTYPE html>
            <html lang="en">
            <head>
              <meta charset="UTF-8">
              <title>Title</title>
            </head>
            <body>
            <p><b>    LOANING SERVICE AGREEMENT    </b></p>
            <p>    This Loaning Service Agreement (the “<b>Agreement</b>”) is made this kloanDate (the “<b>Effective Date</b>”),     </p>
            <p>    Between    </p>
            <p>    <b>LendSafe</b> (an app to obtain loan) operational under the  license of <b>Smartloans Integrated Services Limited</b>, a private limited liability company and having its registered office address at 7, New Hospital Road,Karu, AMAC, FCT (the “<b>Lende</b>r” which expression shall, where the context admits include its successors-in-title and assigns) of the first part;    </p>
            <p>    and kloanName whose address is at kloanAddress, (the “Borrower”, which expression shall, where the context admits include its successors-in-title and assigns) of the second part;    </p>
            <p>    individually erred to as “<b>Party</b>”, and collectively “the <b> Parties.</b>”    </p>
            <p><b>    WHEREAS    </b></p>
            <p>    a. Smartloans Integrated Services  Limited does the business of Money Lending by means of its loan app, ‘LendSafe’ .    </p>
            <p>    b. The Borrower is a  Nigerian citizen living in Nigeria and an adult, above the age 18 years old    </p>
            <p>    c. The Borrower is desirous of borrowing the sum of kloanMoney from the Lender on the    terms and conditions the Lender set hereunder.    </p>
            <p><b>    IN CONSIDERATION of, the covenants, and conditions contained herein, the Parties agree as follows:    </b></p>
            <p><b>    1. CONDITIONS AND MEANS OF OBTAINING A LOAN FROM THE LENDER    </b></p>
            <p>    a. The Borrower may obtain loans from the Lender through Lendsafe loan ranging from ₦5,000 to ₦600,000, contingent upon regular use of the Lender’s services and fulfillment of the following conditions:    </p>
            <p>     i. The Borrower must be an adult above 18 years.    </p>
            <p>     ii. The Borrower must be a Nigerian residence and a Nigerian    </p>
            <p>     iii. The Borrower must be financial capable to refund the loan on or before the due date.    </p>
            <p>     iv. The Borrower must provide to the Lender an accurate and verifiable information including name, email address, phone number, BVN, bank details and any other details that the Lender requires as necessary.    </p>
            <p>     v. By proceeding on the loan application by the Borrower, it is deemed that the Borrowers has read and accepted to be bound by this agreement and the Privacy Policy.    </p>
            <p>     vi. The Borrower is required to complete the registration process on the loan application by supplying all requested information, including but not limited to the Borrower’s name, email address, phone number, personal Nigeria bank information, and any other details that may be periodically requested.    </p>
            <p><b>    2. LOAN ADVANCEMENT AND REPAYMENT    </b></p>
            <p>    a. The Lender commits to advance the Borrower a loan in the upon execution of Agreement and fulfillment of any conditions precedent as specified herein.    </p>
            <p>    b. The Borrower agrees to repay the Loan, including any accrued interest within the specified date and pay default fee when the Lender is not refunded within time.    </p>
            <p><b>    3. INTEREST CHARGE    </b></p>
            <p>    a. Interest will be applied at the rate specified by the Lender. The Lender may adjust the interest rate and penalty fee rate in line with market changes at its sole discretion.    </p>
            <p>    b. Repayment installments, as outlined in the Repayment Dates, will occur at regular, agreed-upon intervals. If a repayment installment is due on a non-business day, it may be paid on the next business day, which may result in additional interest accrual. Interest will be calculated daily on the outstanding balance.    </p>
            <p>    c. If the Borrower fails to make a repayment installment by the due date, the Lender will impose the default interest rate to be specified on the unpaid amount. The default interest rate will be effective from the date the payment was due. The default interest rate will be charged in addition to the regular interest rate, calculated and collected in the same manner, and will serve as compensation for the additional risk and administrative costs arising from the Borrower’s failure to make timely payments.    </p>
            <p><b>    4. Late Payment Penalty</b>    </p>
            <p>    In the event of a failure to repay the loan amount by 24:00 hours on the due date, the Borrower shall incur the following penalties:    </p>
            <p>    1. A <b>late payment fee of 3% of the principal amount</b> as an account management fee.    </p>
            <p>    2. A <b> delayed interest charge</b>, calculated as follows:    </p>
            <p>    ·<b> 1.7% flat per day</b> for delays of up to 10 days.    </p>
            <p>    · <b>2.5% flat</b> for delays of 10–20 days.    </p>
            <p>    ·<b> 3% flat</b> for delays exceeding 20 days.    </p>
            <p>    3. The Borrower acknowledges and agrees that these penalties are intended to compensate the Lender for administrative and financial costs resulting from delayed repayment.     </p>
            <p>    4. The Borrower agrees that all penalty fees and delayed interest charges will be added to the outstanding loan balance and repayment of these amounts is required to satisfy the loan obligation in full.    </p>
            <p>    By selecting "Completed," the Borrower confirms their understanding and acceptance of the penalty fee structure as an integral part of this Agreement.    </p>
            <p><b>    5.  DISBURSEMENT OF LOAN    </b></p>
            <p>    The Lender will transfer the Loan to an account designated by the Borrower only after the Borrower has provided all required documentation and fulfilled all conditions precedent outlined in this Agreement.    </p>
            <p><b>    6. BORROWER’S AGREES:    </b></p>
            <p>    a. To use the App in compliance with applicable laws, regulations, and these Terms.    </p>
            <p>    b. To ensure the information provided during the registration process is accurate.    </p>
            <p>    c. Not to disrupt the effective use of the app by engaging in acts that could affect LendSafe operations and security.    </p>
            <p>    d. Not to use LendSafe for fraudulent or unlawful activities.    </p>
            <p>    e. Not to tamper with the Lender’s software or composition used in making LendSafe app.    </p>
            <p>    f. To limit the use of the app only for taking loans or verifying your information only.    </p>
            <p>    g. The Borrower agrees to make timely payments of all principal and interest due under the Loan Agreement according to the agreed-upon repayment schedule and to promptly notify the Lender in writing of any default or significant adverse change in its financial condition.    </p>
            <p>    h. To always update the Lender of change in details of Borrower’s information.    </p>
            <p><b>    7. DEFAULT AND CONSEQUENCES    </b></p>
            <p>    <b>a. Default Events:</b> The following events will constitute a default under this Loan Agreement:    </p>
            <p>     i. Non-Payment: The Borrower fails to make any payment of principal or interest     when due;     </p>
            <p>     ii. Breach: The Borrower breaches any covenant, representation, or warranty in this Agreement, and such breach remains uncorrected for five days following written notice from the Lender;    </p>
            <p>     iii. Misrepresentation: Any representation or information provided by the Borrower    is found to be materially false or misleading;    </p>
            <p>     iv. Material Adverse Change: A significant adverse change occurs in the Borrower’s financial condition, business, operations, or prospects, affecting their ability to repay the loan as determined by the Lender.    </p>
            <p><b>    b.  Consequences of Default: If the Borrower defaults, the Lender may take the following actions:    </b></p>
            <p>     i. Demand immediate repayment of the entire outstanding principal amount, along    with any accrued interest and fees, communicated through various means;    </p>
            <p>     ii. Initiate collection actions, including engaging third-party debt collectors;     </p>
            <p>     iii. Pursue legal proceedings to obtain a judgment for the amount owed;     </p>
            <p>     iv. Report the default to credit bureaus, potentially harming the Borrower's     creditworthiness;     </p>
            <p>     v. Depending on the Borrower’s cooperation and communication, the Lender may     negotiate a settlement to resolve the debt, potentially extending the loan period without legal action.    </p>
            <p><b>    8.  BORROWER FURTHER AGREES:    </b></p>
            <p>    By accepting to be bound by this Agreement, the Borrower hereby agrees to the following:    </p>
            <p>    a. The Borrower authorizes the Lender to collect, store, and use personal and financial information provided in this application and any supporting documentation for the purpose of evaluating and processing the loan application.    </p>
            <p>    b. The Borrower consents to the Lender obtaining credit reports and other relevant financial information from credit reporting agencies or other sources as deemed necessary for assessing the Borrower's creditworthiness.    </p>
            <p>    c. The Borrower agrees to receive communications from the Lender via electronic means, including email, text messages, and other forms of digital communication, regarding the loan application and any related matters.    </p>
            <p>    d. The Borrower acknowledges that any modification to the terms of this Agreement may require additional consent and understanding, which will be documented as necessary.    </p>
            <p>    e. The Borrower confirms that they have read and understood all terms and conditions of this Agreement and voluntarily consent to proceed with the loan application.    </p>
            <p><b>    9. BORROWER’S RIGHT    </b></p>
            <p>    a. <b>Right to be informed:</b> Borrower has the right to receive clear and understandable information about the loans condition, including interest rates, fees, repayment schedule, and any penalties or charges through this agreement and the loan app.    </p>
            <p>    b.<b> Right to Privacy: </b>Lender respect Borrower’s privacy rights. Borrower’s personal information will only be used for the purposes specified in in Lender’s Privacy Policy and will not be shared without your consent, except as required by law.    </p>
            <p>    c.<b> Right to Fair Treatment:</b> The Borrower is entitled to fair and respectful treatment by the Lender throughout the loan process and during the term of the loan.    </p>
            <p>    d. <b>Right to Withdraw Application:</b> Borrower has the right to withdraw the loan application at any time before acceptance of the loan conditions without any penalty or fees.    </p>
            <p>    e. <b>Right to Dispute Resolution: </b>In case of disputes or disagreements regarding the loan agreement, you have the right to contact the Lender to seek clarification or resolution through fair and accessible dispute resolution mechanisms as outlined in the agreement.    </p>
            <p>    f.<b> Right to Loan Repayment Options:</b> Borrower has the right to choose from available repayment options that best suit your financial circumstances, subject to the terms and conditions of the loan agreement.    </p>
            <p>    g.<b> Right to Early Repayment:</b> Borrower has the right to repay the loan early, in whole or in part, at any time without incurring prepayment penalties    </p>
            <p>    h.<b> Right to Information Security:</b> Lender take reasonable measures to ensure the security and confidentiality of your personal and financial information collected during the loan application process.    </p>
            <p><b>    i. Right to Withdraw Consent: Borrower’s consent to receive Communications electronically will remain in effect until Borrower withdraw it. Borrower has the right to withdraw Borrower’s consent to the processing of Borrower’s personal data at any time. Lender will cease processing Borrower personal data for the purposes to which you initially consented, unless there is another legal basis for processing where Borrower withdraw consent.    </b></p>
            <p>    j.<b> Right to Termination:</b> The Borrower has the right to terminate this Agreement under the conditions specified herein, subject to any applicable laws and regulations.    </p>
            <p><b>    10. REPRESENTATION AND WARRANTIES     </b></p>
            <p>    Both Parties represent that they are fully authorized to enter into this Agreement. The performance and obligations of either Party will not violate or infringe upon the rights of any third party or violate any other agreement between the Parties, individually, and any other person, organization, or business or any law or governmental regulation.    </p>
            <p><b>    11. SEVERABILITY    </b></p>
            <p>    In the event any provision of this Agreement is deemed invalid or unenforceable, in whole or in part, that part shall be severed from the remainder of the Agreement and all other provisions shall continue in full force and effect as valid and enforceable.     </p>
            <p><b>    12. ASSIGNABILITY    </b></p>
            <p>    a. The Borrower may not assign or transfer their rights or obligations under this Agreement without the prior written consent of the Lender. The Lender may assign or transfer its rights and obligations under this Agreement in whole or in part without the Borrower's consent.    </p>
            <p>    b. In the event of any assignment or transfer of rights or obligations, the assigning party notify the other party of such assignment.    </p>
            <p>    13.  CONTINUITY OF OBLIGATIONS    </b></p>
            <p>    Any successor or assignee of either party shall be bound by the terms and conditions of this Agreement, and all obligations and rights herein shall continue to be enforceable against such successors or assigns.    </p>
            <p><b>    14. TERMINATION    </b></p>
            <p>    Either Party has the right to terminate this agreement at any time. The Lender is under no obligation to the Borrower to give reason for termination or suspension of service to the Borrower. Where the Borrower terminates the agreement, the Borrower shall fulfill these conditions:    </p>
            <p>    a. The Borrower shall immediately cease all use of the loan application platform and return any borrowed funds or assets in accordance with the terms of the agreement.    </p>
            <p>    b. Upon termination of this Agreement, the Borrower shall remain liable for any outstanding principal, interest, and any fees incurred up to the date of termination and the Lender may demand immediate repayment of the entire outstanding balance of the Loan, including any accrued interest and fees.    </p>
            <p><b>    15. ENTIRE AGREEMENT    </b></p>
            <p>    The Parties acknowledge and agree that this Agreement represents the entire agreement between the Parties. In the event that the Parties desire to change, add, or otherwise modify any terms, they shall do so in writing to be signed by both parties.    </p>
            <p><b>    By clicking or other means on the page, you confirm that you have     </b></p>
            <p><b>    agreed to executed this agreement.    </b></p>

            </body>
            </html>
            
            """
        
        //let replacedString = htmlString.replacingOccurrences(of: "World", with: "Swift")
        
        let replacements: [String: String] = [
            "kloanDate": loanDate,
            "kloanName": loanName,
            "kloanAddress": loanAddress,
            "kloanMoney": loanMoney,
            //            "kloanInterest": loanInterest,
//            "kloanDay": loanDay,
//            "krepaymentDate": repaymentDate,
//            "kpenaltyInterest": penaltyInterest
        ]
        let modifiedString = replacements.reduce(htmlString) { (result, replacement) in
            result.replacingOccurrences(of: replacement.key, with: replacement.value)
        }
        
        if let data = modifiedString.data(using: .utf8) {
            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ]
            
            do {
                let attributedString = try NSAttributedString(data: data, options: options, documentAttributes: nil)
                textView.attributedText = attributedString
            } catch {
                print("Error loading HTML: \(error)")
            }
        }
    }
}
